<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>星星评分</title>
		<style>
			* {
				margin: 0 auto;
				padding: 0;
			}
			.box {
				width: 400px;
				height: 150px;
				border: 2px solid red;
				text-align: center;
			}
			
			.left {
				float: left;
				margin-left: -50px;
				margin-top: 30px;
				width: 500px;
			}
			
			#comment {
				margin-top: 10px;
			}
		</style>
	</head>

	<body>
		<div class="box">
			<div id="stars" class="left">
				<img src="img/shining.png" alt="">
				<img src="img/shining.png" alt="">
				<img src="img/shining.png" alt="">
				<img src="img/shining.png" alt="">
				<img src="img/shining.png" alt="">

			</div>
			<div id="comment" class="left">

			</div>

		</div>

		<script>
			//制作一个星星评分
			var divStars = document.getElementById("stars");
			var divComment = document.getElementById("comment");
			var attitude = ["1颗星", "2颗星", "3颗星", "4颗星", "5颗星"];
			var starNum = -1; //记录当前第几颗星星被点击
			var starArray = Array.from(divStars.children); //星星数组

			//鼠标移入
			divStars.onmouseover = function(e) {
				if(e.target.tagName === "IMG") { //事件源是图片
					//把鼠标移动到的星星替换图片
					e.target.src = "img/empty.png";
					//把鼠标移动到的星星之前的星星替换图片
					var prev = e.target.previousElementSibling;
					while(prev) {
						prev.src = "img/empty.png";
						prev = prev.previousElementSibling;
					}
					//把鼠标移动到的星星之后的星星替换图片
					var next = e.target.nextElementSibling;
					while(next) { //把鼠标移动到的星星之后的星星替换图片
						next.src = "img/shining.png";
						next = next.nextElementSibling;
					}

					var index = starArray.indexOf(e.target); //找到鼠标移动到的星星的序号
					divComment.innerHTML = attitude[index]; //显示对应的评论
					divComment.style.fontSize = "30px";
				}
			}

			//鼠标点击
			divStars.onclick = function(e) {
				if(e.target.tagName === "IMG") {
					//记录当前点击的星星序号
					starNum = starArray.indexOf(e.target);
				}
			}

			//鼠标移出
			divStars.onmouseout = function(e) {
				if(starNum !== -1) { //鼠标点击事件发生，将评分固定在点击的星星上
					for(var i = 0; i < divStars.children.length; i++) {
						if(i <= starNum) {
							divStars.children[i].src = "img/empty.png";

						} else {
							divStars.children[i].src = "img/shining.png";
						}
					}
					divComment.innerHTML = attitude[starNum]; //显示对应的评论
				} else {
					for(var i = 0; i < divStars.children.length; i++) {
						divStars.children[i].src = "img/shining.png";
					}
					divComment.innerHTML = ""; //不显示评论
				}
			}
		</script>
	</body>

</html>